/*
 * @Author: xiaosihan
 * @Date: 2024-09-04 18:35:16
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2024-09-04 18:36:18
 */

import { autorun } from "mobx";
import { ReactNode, useEffect, useRef, useState } from "react";
import styles from "./helix.module.less";
import { Vector2 } from "three";

interface Iprops {
    children?: ReactNode;
}

export default function Helix(props: Iprops) {
    const dom = useRef<HTMLCanvasElement | null>(null);
    const [data, setData] = useState({});

    useEffect(() => {

        if (dom.current) {
            const ctx = dom.current.getContext("2d")!;
            ctx.clearRect(0, 0, 1024, 1024);
            const rotateCenter = new Vector2(0, 0);
            const center = new Vector2(2048, 2048);
            const point = new Vector2();
            ctx.moveTo(2048, 2048);

            let i = 0;
            let angle = 0;
            while (i < 2048) {
                point
                    .set(-1, 0)
                    .rotateAround(rotateCenter, angle * (Math.PI / 180))
                    .setLength(i)
                    .add(center)

                ctx.lineTo(point.x, point.y);

                angle++;
                i += 0.05;
            }

            ctx.lineWidth = 4;
            ctx.strokeStyle = "#000000";
            ctx.stroke();
        }

    }, []);

    // 返回base64
    const toImage = () => {
        if (dom.current) {
            const ctx = dom.current.getContext("2d")!;
            return ctx.canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
        }
        return "";
    }

    // 图片下载
    const downimage = () => {
        const save_link = document.createElementNS("http://www.w3.org/1999/xhtml", "a") as HTMLAnchorElement;
        save_link.href = toImage();
        save_link.download = new Date().getTime() + ".png";
        save_link.click();
    }

    useEffect(() => autorun(() => { }), []);

    return (
        <div className={styles.helix}>
            <button onClick={downimage} >下载</button>
            <canvas
                width={4096}
                height={4096}
                className={styles.canvas}
                ref={dom}
            />
        </div>
    );
}
